<?php 
if (!defined('BASEPATH')) exit('No direct access allowed.'); 

class MY_Controller extends CI_Controller {

	protected $ci;
	public $user_id;
	
    public function __construct() { 
        parent::__construct();
		
		$this->load->database();
		$this->load->helper('url');
		
		$this->load->helper('Functions');

		$this->user_id = 0;
		$this->user_priv = array();
		$this->VerifToken();
    } 


    public function out($data=array()) {
		$time = time();
		
		$arr = array('result_code'=>0,'message'=>'','data'=>'','time'=>$time);
	   
		foreach($data as $key=>$val){
			$arr[$key] = $val;
		}
		echo json_encode($arr);
		exit;
    }
	
	public function data_out($data=array(),$message="获取数据成功"){
		//$data = $this->data_cl($data);
		$arr = array('result_code'=>0,'message'=>$message,'data'=>$data);
	    $this->out($arr);
	}
	
	public function err_out($message,$result_code=1) {
       $arr = array('result_code'=>$result_code,'message'=>$message);
	   $this->out($arr);
    }
	
	function VerifToken(){		

		
		$token = $this->input->post('SToken');		
		$this->load->model('User/UserLoginModel','user_login');		
		$row = $this->user_login->token_get_data($token);
		
		//$row = array('user_id'=>1);
		
		if(!$row){
			$data = array(
				'result_code'=>401,
				 'message'=>'token错误'
			);
			$this->out($data);			
		}		
		$this->user_id = $row['user_id'];
	}
	
	function CheckData($arr=array(),$data=array()){
		//验证参数
		$this->load->library('form_validation');
		
		$config = array();
		
		foreach($arr as $key=>$val){
			if(is_array($val)){
				$ls_arr = array();
				$errors = array();
				
				foreach($val as $k=>$v){
					$ls_arr[] = $k;
					$ls_key = preg_replace("/\[.*/",'',$k);
					$errors[$ls_key] = $v;
				}
				$rules = implode('|',$ls_arr);
			}
			else{
				$rules = 'required';
				$errors = array(
					$rules =>$val
				);
			}
			
			$config[] = array(
					'field' => $key,
					'label' => $key,
					'rules' => $rules,
					'errors' => $errors,
				);
		}
		
		$this->form_validation->set_data($data);
		$this->form_validation->set_rules($config);

		if($this->form_validation->run() === FALSE){
			$err_arr = $this->form_validation->error_array();
			
			return implode(PHP_EOL,$err_arr);
        }
		return false;
	}
	
	function data_filter($data,$arr=null,$no_input=array()){
		$ls_arr = array();
		
		if(is_array($arr)){
			foreach($arr as $key=>$val){
				if(isset($data[$val])){
					$ls_arr[$val] = $data[$val];
				}
			}
		}
		else{
			if(is_array($no_input)){
				foreach($no_input as $key=>$val){
					if(isset($data[$val])){
						unset($data[$val]);
					}
				}
			}
			$ls_arr = $data;
			
		}
		
		return $ls_arr;
	}
} 